from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count
from django.contrib.contenttypes.models import ContentType

import markdown
from markdown.extensions.toc import TocExtension
import re

from .models import BlogType, Blog
from read_record.models import ReadNum
from read_record.utils import increase_read_num
from comment.models import Comment
from comment.forms import CommentForm
from user.forms import LoginForm

def get_blog_list_common_date(request, blogs_all_list):
    paginator = Paginator(blogs_all_list, settings.BLOGS_PER_PAGE) # 每7篇分为一页
    page_num = request.GET.get('page', 1) # 获取页码参数（GET请求）
    page_of_blogs = paginator.get_page(page_num)
    current_page_num = page_of_blogs.number # 当前页码
    # 获取当前页码前后各两页
    page_range = list(range(max(1, current_page_num - 2), min(current_page_num + 3, paginator.num_pages + 1)))
    # 加上页面的省略标记
    if page_range[0] - 1 > 1:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] > 1:
        page_range.append('...')
    # 加上首页和尾页
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.append(paginator.num_pages)
    # 获取博客类别与每一类的数量

    '''
    blog_types = BlogType.objects.all()
    for blog_type in blog_types:
        blog_type.blog_count = Blog.objects.filter(blog_type=blog_type).count()
    '''
    blog_dates = Blog.objects.dates('create_time', 'month', 'DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_dates_dict[blog_date] = Blog.objects.filter(create_time__year=blog_date.year, create_time__month=blog_date.month).count()

    context = {}
    context['page_of_blogs'] = page_of_blogs
    context['blog_types'] = BlogType.objects.annotate(blog_count=Count('blog'))
    context['page_range'] = page_range
    context['blog_dates'] = blog_dates_dict
    return context


# Create your views here.
def blog_list(request):
    blogs_all_list = Blog.objects.all()
    context = get_blog_list_common_date(request, blogs_all_list) 

    return render(request, 'blog/blog_list.html', context)

def blog_detail(request, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    read_cookie_key = increase_read_num(request, blog)

    # 生成id的方法
    def slugify(value, seperator):
        return re.sub(r'\s+', seperator, value)
    # 把blog的内容的markdown渲染成html
    md = markdown.Markdown(extensions=[
                                'markdown.extensions.extra',
                                'markdown.extensions.codehilite',
                                TocExtension(slugify=slugify, anchorlink=True),
                                'markdown_katex',
    ])
    blog.content = md.convert(blog.content)
    # blog.content = markdown.markdown(blog.content, output_format='html5', extensions=[
    #                                     'markdown.extensions.extra',
    #                                     'markdown.extensions.codehilite',
    #                                     'markdown.extensions.toc',
    # ])
    context = {}
    context['blog'] = blog
    # 目录
    context['toc'] = md.toc
    # 超出所有创建时间大于当前文档的最后一个
    context['previous_blog'] = Blog.objects.filter(create_time__gt=blog.create_time).last()
    # 超出所有创建时间大于当前文档的第一个
    context['next_blog'] = Blog.objects.filter(create_time__lt=blog.create_time).first()

    response = render(request, 'blog/blog_detail.html', context)
    response.set_cookie(read_cookie_key, 'true') # 设置一个cookie直到关闭浏览器后无效
    return response

def blogs_with_type(request, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk = blog_type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)

    context = get_blog_list_common_date(request, blogs_all_list)
    context['blog_type'] = blog_type
    return render(request, 'blog/blogs_with_type.html', context)

def blogs_with_date(request, year, month):
    blogs_all_list = Blog.objects.filter(create_time__year=year, create_time__month=month)

    context = get_blog_list_common_date(request, blogs_all_list)
    context['current_date'] = '{}年{}月'.format(year, month)

    return render(request, 'blog/blogs_with_date.html', context)